package com.yaoweigroup.community.ui;

import java.io.File;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import com.yaoweigroup.community.R;
import com.yaoweigroup.community.config.Common;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.dialog.DialogCallBack;
import com.yaoweigroup.community.enity.Version;
import com.yaoweigroup.community.ui.bm.BMHomeActivity;
import com.yaoweigroup.community.ui.go.GoHomeActivity;
import com.yaoweigroup.community.ui.home.MainHomeActivity;
import com.yaoweigroup.community.ui.my.MyHomeActivity;
import com.yaoweigroup.community.util.ApkDownloadUtil;
import com.yaoweigroup.community.util.DialogUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.UtilHttp;
import com.yaoweigroup.community.util.VersionUtil;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.graphics.Color;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TabHost;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;

/**
 * 主页-- Tab
 * 
 * @author xi
 * 
 */
public class MainTabActivity extends Activity implements
		OnCheckedChangeListener {

	private TabHost tabHost;
	private Intent homeIntent;
	private Intent bmIntent;
	private Intent goIntent;
	private Intent myIntent;
	private LocalActivityManager activityGroup;

	private RadioButton radio_btn_home;
	private RadioButton radio_btn_bm;
	private RadioButton radio_btn_go;
	private RadioButton radio_btn_profile;

	private ObjectMapper mapper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_tab);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		homeIntent = new Intent(this, MainHomeActivity.class);
		bmIntent = new Intent(this, BMHomeActivity.class);
		goIntent = new Intent(this, GoHomeActivity.class);
		myIntent = new Intent(this, MyHomeActivity.class);

		tabHost = (TabHost) findViewById(R.id.tabhost);
		activityGroup = new LocalActivityManager(this, true);
		activityGroup.dispatchCreate(savedInstanceState);
		tabHost.setup(activityGroup);
		tabHost.setCurrentTab(0);
		mapper = new ObjectMapper();
		initRadios();
		setupIntent();
		checkVersion();
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			switch (buttonView.getId()) {
			case R.id.radio_btn_home:
				this.tabHost.setCurrentTabByTag("home_tab");
				radio_btn_home.setTextColor(Color.parseColor("#FF4F00"));
				radio_btn_bm.setTextColor(Color.parseColor("#848484"));
				radio_btn_go.setTextColor(Color.parseColor("#848484"));
				radio_btn_profile.setTextColor(Color.parseColor("#848484"));

				break;
			case R.id.radio_btn_bm:
				radio_btn_home.setTextColor(Color.parseColor("#848484"));
				radio_btn_bm.setTextColor(Color.parseColor("#FF4F00"));
				radio_btn_go.setTextColor(Color.parseColor("#848484"));
				radio_btn_profile.setTextColor(Color.parseColor("#848484"));
				this.tabHost.setCurrentTabByTag("bm_tab");
				break;
			case R.id.radio_btn_go:
				radio_btn_go.setTextColor(Color.parseColor("#FF4F00"));
				radio_btn_bm.setTextColor(Color.parseColor("#848484"));
				radio_btn_home.setTextColor(Color.parseColor("#848484"));
				radio_btn_profile.setTextColor(Color.parseColor("#848484"));
				this.tabHost.setCurrentTabByTag("go_tab");
				break;
			case R.id.radio_btn_profile:
				radio_btn_go.setTextColor(Color.parseColor("#848484"));
				radio_btn_bm.setTextColor(Color.parseColor("#848484"));
				radio_btn_home.setTextColor(Color.parseColor("#848484"));
				radio_btn_profile.setTextColor(Color.parseColor("#FF4F00"));
				this.tabHost.setCurrentTabByTag("profile_tab");
				break;
			}
		}
	}

	private void initRadios() {
		radio_btn_home = ((RadioButton) findViewById(R.id.radio_btn_home));
		radio_btn_home.setOnCheckedChangeListener(this);
		radio_btn_bm = ((RadioButton) findViewById(R.id.radio_btn_bm));
		radio_btn_bm.setOnCheckedChangeListener(this);
		radio_btn_go = ((RadioButton) findViewById(R.id.radio_btn_go));
		radio_btn_go.setOnCheckedChangeListener(this);
		radio_btn_profile = ((RadioButton) findViewById(R.id.radio_btn_profile));
		radio_btn_profile.setOnCheckedChangeListener(this);
	}

	private void setupIntent() {
		TabHost localTabHost = this.tabHost;
		localTabHost.addTab(buildTabSpec("home_tab", R.string.home,
				R.drawable.ic_launcher, this.homeIntent));
		localTabHost.addTab(buildTabSpec("bm_tab", R.string.bm,
				R.drawable.ic_launcher, this.bmIntent));
		localTabHost.addTab(buildTabSpec("go_tab", R.string.go,
				R.drawable.ic_launcher, this.goIntent));
		localTabHost.addTab(buildTabSpec("profile_tab", R.string.my,
				R.drawable.ic_launcher, this.myIntent));

	}

	private TabHost.TabSpec buildTabSpec(String tag, int resLabel, int resIcon,
			final Intent content) {
		return this.tabHost
				.newTabSpec(tag)
				.setIndicator(getString(resLabel),
						getResources().getDrawable(resIcon))
				.setContent(content);
	}

	@Override
	protected void onResume() {
		activityGroup.dispatchResume();
		if (activityGroup.getCurrentActivity() instanceof MainHomeActivity) {
			LogUtil.d("wxf", "home");
			MainHomeActivity home = (MainHomeActivity) activityGroup
					.getCurrentActivity();
			home.onResume();
		} else if (activityGroup.getCurrentActivity() instanceof MyHomeActivity) {
			LogUtil.d("wxf", "home");
			MyHomeActivity my = (MyHomeActivity) activityGroup
					.getCurrentActivity();
			my.onResume();
		}
		LogUtil.d("wxf", "main onResume");
		super.onResume();
	}

	public final int GET_VERSION_FAIL = 0x2210;
	public final int GET_VERSION_SUCCESS = GET_VERSION_FAIL + 1;
	public final int NEW_VERSION = GET_VERSION_SUCCESS + 2;
	public final int NO_NEW_VERSION = GET_VERSION_SUCCESS + 3;
	private Version version;

	private void checkVersion() {
		HttpUtils http = UtilHttp.getHttpUtils(this);
		http.send(HttpRequest.HttpMethod.POST, Urls.version,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {

						handler.sendEmptyMessage(GET_VERSION_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {

						String result = arg0.result;
						LogUtil.d("wxf", "version =" + result);
						try {
							JSONObject obj = new JSONObject(arg0.result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							if (state == 200) {
								version = mapper.readValue(data,
										new TypeReference<Version>() {
										});
								int currentCode = VersionUtil
										.getCurrentLocalVersion(MainTabActivity.this);
								if (version.getVersionCode() > currentCode) {
									Message msg = handler.obtainMessage();
									msg.what = NEW_VERSION;
									handler.sendMessage(msg);
								} else {
									Message msg = handler.obtainMessage();
									msg.what = NO_NEW_VERSION;
									handler.sendMessage(msg);
								}
							} else {

							}
						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
							handler.sendEmptyMessage(GET_VERSION_FAIL);

						}
					}

				});

	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GET_VERSION_FAIL:

				break;
			case GET_VERSION_SUCCESS:

				break;
			case NEW_VERSION:
				DialogUtil.versionDialog(MainTabActivity.this,
						version.getVersionDes(), new DialogCallBack() {

							@Override
							public void viewClick() {

							}

							@Override
							public void ok() {
								try {
									ApkDownloadUtil util = new ApkDownloadUtil(
											getApplicationContext(),
											handler,
											version.getApkUrl(),
											String.valueOf(getText(R.string.app_name)
													+ "_"
													+ VersionUtil
															.getVersionName(MainTabActivity.this)));
									util.start();
								} catch (Exception e) {
								}
							}

							@Override
							public void init(Object obj) {

							}

							@Override
							public void cancel() {

							}
						}, "升级", "取消");
				break;
			case ApkDownloadUtil.MSG_DOWNING:
				Toast.makeText(getApplicationContext(), R.string.downloadStart,
						Toast.LENGTH_LONG).show();
				break;
			case ApkDownloadUtil.MSG_FINISH:
				String path = (String) msg.obj;
				installAPK(path);
				break;
			case ApkDownloadUtil.MSG_FAILURE:
				Toast.makeText(getApplicationContext(),
						R.string.downloadFailure, Toast.LENGTH_LONG).show();
				break;
			}

		};
	};

	private void installAPK(String path) {

		Uri uri = Uri.fromFile(new File(path));
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		startActivity(intent);
	}

}
